import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:xiaozhou_ams_flutter/tools.dart';
import 'memo/addMemo.dart';
import 'api_client.dart';

// 备忘录模型
class Memo {
  String id;
  String title;
  DateTime updateTime;

  Memo({required this.id, required this.title, required this.updateTime});
}

class Token{
  static Future<String?>getToken() async{
    final prefs = await SharedPreferences.getInstance();
    final String? token = prefs.getString('userToken');
    if (kDebugMode) {
      print("token is :$token");
    }
    return token;
  }
}
// 备忘录管理器
class MemoManager {
  List<Memo> memos = [];
  String memoListUrl = 'memo/memoList';
  String deleteMemoUrl = 'memo/deleteMemo';

  MemoManager() {
    initMemos();
  }

  void initMemos() async {
    // 载入备忘录数据
    await getMemo();
  }
  Future<void> getMemo() async {
    final response = await ApiClient.sendGetRequest(memoListUrl);

    if (response != null) {
      Map<String, dynamic> jsonMap = json.decode(response);

      // 获取 success、msg、data
      bool success = jsonMap['success'];
      String msg = jsonMap['msg'];

      try {
        if (success) {
          // 清除现有的备忘录
          memos.clear();
          List <dynamic> data = jsonMap['data'];
          for(var memoList in data){
            addMemo(memoList['id'].toString(),
                memoList['title'].toString(),
                DateTime.parse(memoList['createDate']));
          }
        } else {
          if (kDebugMode) {
            print('memo list failed!');
          }
          SnackbarHelper.showToast(msg);
        }
      } catch (error) {
        if (kDebugMode) {
          print('memo list failed!');
        }
        SnackbarHelper.showToast("系统错误，请联系统管理员！");
      }
    }
  }

  void addMemo(String id,String title,DateTime updateTime) {
    if (memos.any((memo) => memo.id == id)) {
      // 跳过相同的数据
      return;
    }
    final memo = Memo(id: id, title: title, updateTime: updateTime);
    memos.add(memo);
    memos.sort((a, b) => b.updateTime.compareTo(a.updateTime));
  }
  void careMemo(){
    memos.clear();
  }
  Future<void> deleteMemo(String id,int index) async {

    final formData = {
      'id': id
    };
    final response = await ApiClient.sendPostRequest(deleteMemoUrl, formData);
    if (response != null) {
      Map<String, dynamic> jsonMap = json.decode(response);
      // 获取 success
      bool success = jsonMap['success'];
      try {
        if (success) {
          memos.removeWhere((memo) => memo.id == id);
          memos.removeAt(index);
          SnackbarHelper.showToast("已经成功消灭这条备忘录！");
        } else {
          SnackbarHelper.showToast("消灭失败，请联系系统管理员");
        }
      }catch (error) {
        if (kDebugMode) {
          print('memo list failed!');
        }
        SnackbarHelper.showToast("系统错误，请联系统管理员！");
      }
    }

  }

  List<Memo> searchMemos(String query) {
    return memos.where((memo) => memo.title.contains(query)).toList();
  }
}

// 备忘录列表页面
class MemoListPage extends StatefulWidget {
  const MemoListPage({Key? key}) : super(key: key);

  @override
  _MemoListPageState createState() => _MemoListPageState();
}

class _MemoListPageState extends State<MemoListPage> {
  bool isRefreshing = false;
  final MemoManager memoManager = MemoManager();
  String searchQuery = '';


  @override
  void initState() {
    super.initState();
    _initMemos();
  }

  Future<void> _initMemos() async {
    memoManager.memos.clear(); // 清除现有的备忘录
    await memoManager.getMemo(); // 等待备忘录数据加载完成
    setState(() {}); // 重新构建界面

  }

  Future<void> _refreshMemos() async {
    setState(() {
      isRefreshing = true;
    });

    memoManager.initMemos(); // 初始化备忘录

    setState(() {
      isRefreshing = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    List<Memo> filteredMemos = searchQuery.isEmpty ? memoManager.memos : memoManager.searchMemos(searchQuery);

    return Scaffold(
      appBar: AppBar(
        title: const Text('记事本'),
        automaticallyImplyLeading: false,
        actions: <Widget>[
          IconButton(
            icon: const Icon(Icons.search),
            onPressed: () {
              showSearch(context: context, delegate: MemoSearchDelegate(memoManager));
            },
          ),
        ],
      ),
      body: RefreshIndicator(
        onRefresh: _refreshMemos,
        child: Stack(
          children: [
            ListView.builder(
              padding: const EdgeInsets.symmetric(vertical: 16.0),
              itemCount: filteredMemos.length,
              itemBuilder: (context, index) {
                final memo = filteredMemos[index];
                return GestureDetector(
                  onTap: (){
                    getMemoUrl(memo.id);
                    if (kDebugMode) {
                      print('点击了id为${memo.id}的备忘录');
                    }
                  },
                  child: Dismissible(
                    key: Key(memo.id),
                    direction: DismissDirection.endToStart,
                    onDismissed: (direction) async {
                      await memoManager.deleteMemo(memo.id,index);
                      setState(() {
                      });
                    },
                    confirmDismiss: (DismissDirection direction) async {
                      // 显示删除确认对话框
                      return await showDialog(
                        context: context,
                        builder: (BuildContext context) {
                          return AlertDialog(
                            title: const Text("确认删除"),
                            content: const Text("你确定要消灭这个备忘录吗？"),
                            actions: <Widget>[
                              TextButton(
                                onPressed: () => Navigator.of(context).pop(false),
                                child: const Text("取消"),
                              ),
                              TextButton(
                                onPressed: () => Navigator.of(context).pop(true),
                                child: const Text("消灭"),
                              ),
                            ],
                          );
                        },
                      );
                    },
                    child: Card(
                      elevation: 2.0,
                      margin: const EdgeInsets.symmetric(horizontal: 16,vertical: 8),
                      child: ListTile(
                        title: Text(
                          memo.title,
                          style: const TextStyle(fontSize: 16,fontWeight: FontWeight.bold),
                        ),
                        subtitle: Text(
                          '修改时间：${memo.updateTime}',
                          style: const TextStyle(fontSize: 14),
                        ),
                      ),
                    ),
                  ),
                );
              },
            ),
            if (isRefreshing)
              const Center(
                child: CircularProgressIndicator(),
              ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          getAddMemoUrl();
        },
        child: const Icon(Icons.add),
      ),
    );
  }

  void getAddMemoUrl() async {
    String? token = await Token.getToken();
    // 确保 token 不为空
    if (token != null) {
      // 使用获得的 token 构建 URL
      String url = 'http://memo.aiyuye.shop/#/?status=2&token=$token';
      // 使用 Navigator 跳转到新页面
      print(url);
      _navigateToMemoListScreen(url);
    } else {
      // 如果 token 为空，处理错误或者提醒用户
      if (kDebugMode) {
        print("Token is null");
      }
    }
  }

  void getMemoUrl(String id) async {
    String? token = await Token.getToken();
    // 确保 token 不为空
    if (token != null) {
      // 使用获得的 token 构建 URL
      String url = 'http://memo.aiyuye.shop/#/?id=$id&status=1&token=$token';
      if (kDebugMode) {
        print(url);
      }
      // 使用 Navigator 跳转到新页面
      _navigateToMemoListScreen(url);
    } else {
      // 如果 token 为空，处理错误或者提醒用户
      if (kDebugMode) {
        print("Token is null");
      }
    }
  }

  void _navigateToMemoListScreen(String url){
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => MyRichTextEditor(url: url,),
      ),
    ).then((value) {
      _initMemos();
    });
  }
}

// 搜索代理
class MemoSearchDelegate extends SearchDelegate {
  final MemoManager memoManager;

  MemoSearchDelegate(this.memoManager) : super(searchFieldLabel: "请输入你要搜索的备忘录");

  @override
  ThemeData appBarTheme(BuildContext context) {
    final ThemeData theme = Theme.of(context);
    return theme.copyWith(
      inputDecorationTheme: const InputDecorationTheme(
        hintStyle: TextStyle(color: Colors.black38), // 自定义提示文本的样式
      ),
      textTheme: const TextTheme(
        titleLarge: TextStyle(color: Colors.black), // 修改搜索框内文本的样式
      ),
    );
  }

  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(
        icon: const Icon(Icons.clear),
        onPressed: () {
          query = '';
        },
      ),
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
      icon: const Icon(Icons.arrow_back),
      onPressed: () {
        close(context, null);
      },
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    // 根据搜索查询获取备忘录列表
    final suggestions = memoManager.searchMemos(query);
    return ListView.builder(
      itemCount: suggestions.length,
      itemBuilder: (context, index) {
        // 从搜索建议中获取单个备忘录
        final memo = suggestions[index];
        return ListTile(
          title: Text(memo.title),
          onTap: () {
            getMemoUrl(context,memo.id);
          },
        );
      },
    );
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    final suggestions = memoManager.searchMemos(query);
    return ListView.builder(
      itemCount: suggestions.length,
      itemBuilder: (context, index) {
        final suggestion = suggestions[index];
        return ListTile(
          title: Text(suggestion.title),
          onTap: () {
            query = suggestion.title;
            showResults(context);
          },
        );
      },
    );
  }
  void getMemoUrl(BuildContext context,String id) async {
    String? token = await Token.getToken();
    // 确保 token 不为空
    if (token != null) {
      // 使用获得的 token 构建 URL
      String url = 'http://memo.aiyuye.shop/#/?id=$id&status=1&token=$token';
      if (kDebugMode) {
        print(url);
      }
      // 使用 Navigator 跳转到新页面
      _navigateToMemoListScreen(context,url);
    } else {
      // 如果 token 为空，可能需要处理错误或者提醒用户
      if (kDebugMode) {
        print("Token is null");
      }
    }
  }
  void _navigateToMemoListScreen(BuildContext context, String url){
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => MyRichTextEditor(url: url,),
      ),
    );
  }
}
